package com.hevery.security.browser;

import com.hevery.security.browser.support.SimpleResponse;
import com.hevery.security.core.properties.SecurityProperties;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: zhy
 * @description:
 * @date: created on 2017/10/23
 * @modified by:
 */
@RestController
public class BrowserSecurityController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**把当前的请求缓存到Session里面去*/
    private RequestCache requestCache = new HttpSessionRequestCache();

    /**Spring中重定向工具*/
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Autowired
    private SecurityProperties securityProperties;

    /**
     * 当需要身份认证时，跳转到这里，来处理需要身份认证的请求
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/authentication/require")
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    public SimpleResponse requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException{

        /**SavedRequest就是之前缓存的请求*/
        SavedRequest savedRequest = requestCache.getRequest(request,response);

        if(savedRequest != null){
            /**获取缓存中引发跳转的url*/
            String targetUrl = savedRequest.getRedirectUrl();
            logger.info("引发跳转的请求是："+targetUrl);
            if(StringUtils.endsWithIgnoreCase(targetUrl,".html")){
                /**因为这是一个公用的模块，所以我们不可能直接跳转到登录模块；而是让使用模块的人可以自己配置是使用自己的登录页还是标准登录页*/
                redirectStrategy.sendRedirect(request, response,securityProperties.getBrowser().getLoginPage());
            }
        }
        /**返回一个对象然后转换为JSON*/
        return new SimpleResponse("访问的服务需要身份认证，请引导用户到登录页");
    }
}
